package com.TinyBBS.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectDB extends Config {

	private static Connection conn = null;
	private static ConnectDB cdb = null;

	private ConnectDB() {}
	/**
	 * Create an instance of connectDb
	 * @return connectDb Object
	 */
	public static ConnectDB getInstance() {
		if (cdb == null) {
			cdb = new ConnectDB();
		}
		return cdb;
	}
	/**
	 * Open a database connection if it is connection is null or closed
	 * @return a database connection
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public Connection connect() throws SQLException, ClassNotFoundException {
		if (conn == null || conn.isClosed()) {
			openConnection();
		}
		return conn;
	}
	/**
	 * Open a database
	 * @throws SQLException
	 * @throws ClassNotFoundException
	 */
	public void openConnection() throws SQLException, ClassNotFoundException {
		Class.forName(super.DB_DRIVER);
		conn = DriverManager.getConnection(super.DB_URL, super.DB_USER,
				super.DB_PASS);
	}
	/**
	 * Close a database
	 * @throws SQLException
	 */
	public void close() throws SQLException{
		if(conn!=null){
			conn.close();
		}
	}
}
